package codegenerator.generator;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;

import baytony.util.Util;
import baytony.util.log.Log;
import codegenerator.CodeGeneratorException;
import codegenerator.FileBean;
import codegenerator.GeneratorHelper;
import codegenerator.TableInfo;


public abstract class XmlGenerator implements IGenerator {
	
	private final Logger logger = Log.getLogger();	
	protected GeneratorHelper generatorHelper;

	public void setGeneratorHelper(GeneratorHelper generatorHelper) {
		this.generatorHelper = generatorHelper;
	}

	@Override
	public void generate(TableInfo... tables) throws CodeGeneratorException {
		logger.trace("*** execute generate ***");
		if(Util.isEmptyArray(tables)) {
			throw new CodeGeneratorException("*** No tables error, check database information is correct or not ***");
		}
		FileBean fb = this.createInfo(tables);
		this.touchFile(fb);
	}
	
	@Override
	public void touchFile(FileBean fb) {
		File file = new File(generatorHelper.getOutputPath() + fb.getPath() + fb.getFileName() + fb.getExtName());
		try {
			FileUtils.writeStringToFile(file, fb.getContent(), generatorHelper.getFileEncode());
		} catch (IOException e) {
			logger.error("create file fail, fileName : " + fb.getFileName());
			Log.logStackTrace(e);
		}
	}
	
	/**
	 * 讀取.jtmp中的內容
	 *
	 * @param jtmpName
	 * @return
	 */
	protected String readJtmp(String jtmpName) {
		File file = new File(generatorHelper.getJtmpPath() + jtmpName);
		String content = "";
		try {
			content = FileUtils.readFileToString(file, generatorHelper.getFileEncode());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	
	public abstract FileBean createInfo(TableInfo...tables) throws CodeGeneratorException;
	
}
